using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PlayTime
{
    public partial class BridgeTableDisplay : Form
    {
        private int nCardHeight = 110;
        private int nCardWidth = 80;
        private int nMargin = 20;
        private int nVerticalCardDistance = 20;
        private int nHorizantalCardDistance = 20;
        private int nHeight = 0;
        private int nWidth = 0;

        private static BridgeTableDisplay singleInstance = null;
        private string m_cGameName;
        private Bridge m_cBridgeEngine = null;
        private Hand m_cHand = null;
        public static BridgeTableDisplay getInstance()
        {
            if (singleInstance == null)
            {
                singleInstance = new BridgeTableDisplay();
            }
            return singleInstance;
        }

        private BridgeTableDisplay()
        {
            InitializeComponent();
        }
        public void ClickHandler(Object sender, System.EventArgs e)
        {
            object tag = ((System.Windows.Forms.PictureBox)sender).Tag;
            string strPos = ((System.Windows.Forms.PictureBox)sender).Name;


            Position posClicker = PlayTime.Bridge.getPosition(strPos);
            if ((m_cBridgeEngine == null)|| (m_cBridgeEngine.Session == null))
            {
                return;
            }
            if ((m_cHand == null) || (m_cHand.Trick == null))
            {
                return;
            }
            BridgePlayer player = m_cBridgeEngine.Session.getPlayer(m_cHand.Trick.NextPositionToLead);
            if (player.Position != posClicker)
            {
                return;
            }

            // System.Windows.Forms.MessageBox.Show("You have clicked button " + tag.ToString());
            Card card = new Card((string)tag);

            bool bLeadStatus = m_cHand.isValidLead(card, player);
            if (bLeadStatus == true)
            {
                TrickStatus eTrickStatus = m_cHand.Lead(card, player);
                PutCardInTrickWindow(player.Position, card);
                ReDrawSinglePlayer(player);
                switch (eTrickStatus)
                {
                    case TrickStatus.CurrentTrickComplete:
                        UpdateNextPlayerToLead();                        
                        ClearTrickWindow();
                        break;
                    case TrickStatus.CurrentTrickInComplete:
                        UpdateNextPlayerToLead();
                        break;
                    case TrickStatus.AllTrickCompleted:
                        m_cHand.State = HandState.Score;
                        HideTrickWindow();
                        break;
                }
            }
            UpdateSessionInfo();
        }

        private void UpdateSessionInfo()
        {
            System.Windows.Forms.Label aLabel = null;

            foreach (Position pos in Position.GetValues(typeof(Position)))
            {
                switch (pos)
                {
                    case Position.East:
                        aLabel = lblEastInfo;
                        break;
                    case Position.West:
                        aLabel = lblWestInfo;
                        break;
                    case Position.South:
                        aLabel = lblSouthInfo;
                        break;
                    case Position.North:
                        aLabel = lblNorthInfo;
                        break;
                }
                if (m_cBridgeEngine.Session!=null)
                {                    
                    BridgePlayer player = m_cBridgeEngine.Session.getPlayer(pos);                
                    UpdateInfoSinglePlayer(aLabel, player);
                }              
            }
            UpdateNextPlayerToLead();
            UpdateDealerName();
        }
       
        private void UpdateInfoSinglePlayer(Label aLabel, BridgePlayer player)
        {
            if ((aLabel == null)|| (player==null))
            {
                return;
            }
            string str;
            str = player.Position.ToString();
            str += "\n";
            
            str += player.Name;
            str += "\n";
            aLabel.Text = str;
        }
        private void UpdateDealerName()
        {
            if ((m_cBridgeEngine.Session == null) || (m_cBridgeEngine.Session.Dealer == null))
            {
                return;
            }
            else
            {
                lblDealerInfo.Text = "Dealer : " + m_cBridgeEngine.Session.Dealer.Position.ToString();
            }
        }
        private void UpdateNextPlayerToLead()
        {            
            if ((m_cBridgeEngine.Session!=null)&&(m_cBridgeEngine.Session.Hand != null) && (m_cBridgeEngine.Session.Hand.Trick != null))
            {                
                lblTolead.Text = m_cHand.Trick.NextPositionToLead.ToString() + " to lead";
            }
        }

        private void ClearTrickWindow()
        {
            picEast.Image = null;
            picWest.Image = null;
            picSouth.Image = null;
            picNorth.Image = null;
        }
        private void HideTrickWindow()
        {
            picEast.Visible = false;
            picWest.Visible = false;
            picSouth.Visible = false;
            picNorth.Visible = false;
        }
        private void ReDrawSinglePlayer(BridgePlayer player)
        {
            RemoveDisplayPosition(player);
            ShowCardSinglePosition(player);
        }

        private void RemoveDisplayPosition(BridgePlayer player)
        {
            string nameControl = player.Position.ToString();
            System.Windows.Forms.Control[] arrButton = null;
            arrButton = this.Controls.Find(nameControl, true);
            for (int i = 0; i < arrButton.Length; i++)
            {
                this.Controls.Remove(arrButton[i]);
            }
        }

        private void BridgeTableDisplay_Load(object sender, EventArgs e)
        {
            m_cGameName = "ContractBridge";
            PlayTime.Factory.GameName = m_cGameName;
            m_cBridgeEngine = PlayTime.Factory.getGameEngine(m_cGameName);

            this.MaximizeBox = false;
            this.AutoSize = false;

            btnPlay.Top = this.Height / 2;
            btnPlay.Left = this.Width / 2;
            nHeight = this.Height;
            nWidth = this.Width;
            m_cBridgeEngine.NewSession(m_cGameName);
            HideTrickWindow();
            UpdateSessionInfo();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_cBridgeEngine.NewSession(m_cGameName);
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            switch (btnPlay.Text)
            {
                case "Deal":
                    m_cBridgeEngine.Session.Deal();
                    break;
                case "Auction":
                    m_cBridgeEngine.Session.Auction();
                    m_cHand = m_cBridgeEngine.Session.Hand;
                    break;
                case "Play":
                    //m_cBridgeEngine.Session.Play();
                    break;
                case "Score":
                    m_cBridgeEngine.Session.Score();
                    break;

            }
        }
        public void eventStateChange(object state)
        {
            if (m_cHand == null)
            {
                if ((m_cBridgeEngine.Session!=null)&& (m_cBridgeEngine.Session.Hand!=null))
                {                
                    m_cHand = m_cBridgeEngine.Session.Hand;
                }
            }
            btnPlay.Text = state.ToString();
            if (state.ToString() == "Play")
            {
                btnPlay.Visible = false;
                //btnEast.Top = btnWest.Top = this.Width / 2;
                //btnEast.Top = btnWest.top = 
                //btnSouth.Left = btnNorth.Left = this.Height / 2; 
                //btnSouth.Left = btnNorth.Left =
            }
            UpdateSessionInfo();
        }


        internal void ShowCardAllPosition()
        {
            Session session = PlayTime.Factory.getSession(m_cGameName);
            for (Position pos = Position.North; pos <= Position.West; pos++)
            {
                BridgePlayer player = session.getPlayer(pos);
                player.ArrangeCard();
                ShowCardSinglePosition(player);
            }
        }

        private void ShowCardSinglePosition(BridgePlayer player)
        {
            switch (player.Position)
            {
                case Position.North:
                case Position.South:
                    DrawNorthSouth(player);
                    break;
                case Position.East:
                case Position.West:
                    DrawEastWest(player);
                    break;
            }
        }


        private void DrawEastWest(BridgePlayer player)
        {
            int dx = -nHorizantalCardDistance;
            int dy = nVerticalCardDistance + nCardHeight;

            int X0 = nMargin;
            int Y0 = nHeight / 2 - 2 * dy; ;

            Card[] hand = player.GetHand();
            int nMaxSuitSize = player.MaxSuitLength;
            if (player.Position == Position.West)
            {
                X0 = nMargin + (nMaxSuitSize - 1) * nVerticalCardDistance;
            }
            else if (player.Position == Position.East)
            {
                X0 = nWidth - nMargin - nCardWidth;
            }
            int X = X0;
            int Y = Y0;

            foreach (CardSuit cs in CardSuit.GetValues(typeof(CardSuit)))
            {
                X = X0;
                for (int handIndex = 0; handIndex < hand.Length; handIndex++)
                {
                    Card card = hand[handIndex];
                    if (card.CardSuit.ToString() == cs.ToString())
                    {
                        ShowCard(player.Position, card, X, Y);
                        X += dx;
                    }
                }
                Y += dy;
            }
        }

        private void DrawNorthSouth(BridgePlayer player)
        {
            int dx = nCardWidth;
            int dy = -nVerticalCardDistance;

            int X0 = nWidth / 2 - dx;
            int Y0 = nMargin;

            Card[] hand = player.GetHand();
            int nMaxSuitSize = player.MaxSuitLength;// hand.Length;
            if (player.Position == Position.South)
            {
                Y0 = nHeight - nMargin - nCardHeight - 40;
            }
            else if (player.Position == Position.North)
            {
                Y0 = nMargin + (nMaxSuitSize - 1) * nVerticalCardDistance + 10;
            }
            int Y = Y0;
            int X = X0;
            foreach (CardSuit cs in CardSuit.GetValues(typeof(CardSuit)))
            {
                Y = Y0;
                for (int handIndex = 0; handIndex < hand.Length; handIndex++)
                {
                    Card card = hand[handIndex];
                    if (card.CardSuit.ToString() == cs.ToString())
                    {
                        ShowCard(player.Position, card, X, Y);
                        Y += dy;
                    }
                }
                X += dx;
            }
        }
        private void ShowCard(Position pos, Card card, int X, int Y)
        {
            System.Windows.Forms.PictureBox aPic = new System.Windows.Forms.PictureBox();
            aPic.Click += new System.EventHandler(ClickHandler);
            aPic.MouseHover += new System.EventHandler(MouseHoverHandler);
            aPic.Left = X;
            aPic.Top = Y;
            aPic.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            aPic.Image = Resources.GetImage(card.GetImageName());
            this.Controls.Add(aPic);
            string symboltext = card.GetSymbolText();
            aPic.Tag = symboltext;
            aPic.Name = pos.ToString();
            aPic.Text = symboltext;
        }

        private void PutCardInTrickWindow(Position position, Card card)
        {
            System.Windows.Forms.PictureBox aButton = new System.Windows.Forms.PictureBox();
            switch (position)
            {
                case Position.East:
                    aButton = picEast;
                    break;
                case Position.West:
                    aButton = picWest;
                    break;
                case Position.North:
                    aButton = picNorth;
                    break;
                case Position.South:
                    aButton = picSouth;
                    break;
            }
            aButton.Image = Resources.GetImage(card.GetImageName());
            aButton.AutoSize = true;
            aButton.Visible = true;

        }
        public void MouseHoverHandler(Object sender, System.EventArgs e)
        {
            //object tag = ((System.Windows.Forms.PictureBox)sender).Tag;
            //((System.Windows.Forms.PictureBox)sender).System.Windows.Forms.MessageBox.Show("You have clicked button " + tag.ToString());
            //frmHost.Controls.Remove(((System.Windows.Forms.PictureBox)sender));
        }


































        private void OpenFile(object sender, EventArgs e)
        {
            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            //if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            //{
            //    string FileName = openFileDialog.FileName;
            //    // TODO: Add code here to open the file.
            //}
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            //if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            //{
            //    string FileName = saveFileDialog.FileName;
            //    // TODO: Add code here to save the current contents of the form to a file.
            //}
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard.
        }



        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }
    }
}
